#include "file_description.h"

#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>

FileDescription::FileDescription(const std::string & file_name, const int mode)
{
    m_file_name        = file_name;
    m_file_description = -1;
    m_file_mode        = mode;
}

FileDescription::~FileDescription()
{
    FileDescription::CloseDescription();
}

int FileDescription::CreateDescription()
{
    int mode = 0;
    if (m_file_mode & ONLYRD)
    {
        mode |= O_RDONLY;
    }
    if (m_file_mode & RDWR)
    {
        mode |= O_RDWR | O_CREAT | O_TRUNC;
    }
    if (m_file_mode & WRAPP)
    {
        mode |= O_APPEND | O_RDWR | O_CREAT;
    }
    int result = open(m_file_name.c_str(), mode, 0666);
    if (result < 0)
    {
        return -1;
    }
    m_file_description = result;
    return 1;
}

void FileDescription::CloseDescription()
{
    if (m_file_description >= 0)
    {
        close(m_file_description);
        m_file_description = -1;
    }
}

int FileDescription::DescriptionData()
{
    return m_file_description;
}
